package io.gitee.welson.sensitive.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 脱敏策略工厂
 *
 * @author welson
 */
@Component
public class SensitiveStrategyFactory {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 策略缓存，key为策略类型，value为策略实例
     */
    private final Map<Class<? extends SensitiveStrategy>, SensitiveStrategy> strategyCache = new HashMap<>();

    /**
     * 初始化策略缓存
     */
    @PostConstruct
    public void init() {
        // 获取所有实现了SensitiveStrategy接口的Bean
        Map<String, SensitiveStrategy> strategyBeans = applicationContext.getBeansOfType(SensitiveStrategy.class);

        // 遍历所有策略Bean
        for (SensitiveStrategy strategy : strategyBeans.values()) {
            strategyCache.put(strategy.getClass(), strategy);
        }
    }

    /**
     * 获取指定类型的脱敏策略
     *
     * @param strategyClass 策略类
     * @return 脱敏策略实例
     */
    public SensitiveStrategy getStrategy(Class<? extends SensitiveStrategy> strategyClass) {
        if (strategyClass == null) {
            return null;
        }

        return strategyCache.get(strategyClass);
    }

}